package com.bktech.stupidnews;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;

import com.bktech.elements.SuggestionListAdapter;
import com.bktech.elements.SuggestionPage;
import com.bktech.fragment.ViewFragment;
import com.bktech.service.ServiceHandler;
import com.bktech.stupidnews.controlpanel.AddPanel;
import com.bktech.stupidnews.controlpanel.Category;
import com.bktech.stupidnews.controlpanel.Category.TYPE;
import com.bktech.stupidnews.controlpanel.ChildCategory;
import com.bktech.stupidnews.controlpanel.HomePanel;

public class MainActivity extends FragmentActivity {
	private final String DEBUG_TAG = MainActivity.class.getName();

	// Within which the entire activity is enclosed
	private DrawerLayout mDrawerLayout;

	// ListView represents Navigation Drawer
	private FrameLayout mDrawerPanelSetting;

	private LinearLayout mDrawerSearch;

	private SearchView searchView;

	private ListView suggestionList;

	ServiceHandler handler;

	// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the
	// action bar
	private ActionBarDrawerToggle mDrawerToggle;

	// Title of the action bar

	private FragmentManager fragmentManager;

	public ViewFragment viewFragment;

	private SuggestionListAdapter adapterSuggest;

	// Key to search
	public String keySearch = "";
	public String keyPreviousSearch = "-";
	public boolean searchRunning = false;

	// For fragment view
	public boolean isNewPage = false;
	// Load from our server
	public ArrayList<Category> dataUser;

	private Fragment fragmentSettingPanel;

	/*
	 * To test
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		handler = new ServiceHandler();

		// Data User
		dataUser = new ArrayList<Category>();
		for (int i = 0; i < 10; i++) {
			Category cat = new Category(TYPE.CATEGORY, "Category " + i);
			for (int j = 0; j < 3; j++) {
				cat.add(new ChildCategory(
						"feed/http://bongdaplus.vn/rss/trang-chu.rss",
						"BongDa.com.vn: Bóng đá quốc tế, bóng đá việt nam",
						"http://storage.googleapis.com/site-assets/iJTudh-t7l4ljWNfROd-0aglkF9f_a7W9GgzVBClPck_icon-1484154aec4"));
			}
			dataUser.add(cat);
		}

		adapterSuggest = new SuggestionListAdapter(this);

		// Getting reference to the DrawerLayout
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		mDrawerPanelSetting = (FrameLayout) findViewById(R.id.drawer_panel_setting_container);

		mDrawerSearch = (LinearLayout) findViewById(R.id.drawer_search);

		searchView = (SearchView) findViewById(R.id.search_view);

		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				Log.d(DEBUG_TAG, "onTextSubmit " + query);
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				Log.d(DEBUG_TAG, "onQueryTextChange  " + newText);
				String newKey = formatKeySearch(newText);
				if (!newKey.equals("")) {
					keySearch = newKey;
				}
				if (searchRunning) {
					return false;
				}
				if (!keySearch.equals(keyPreviousSearch)) {
					new GetSuggest(keySearch).execute();
				}
				return false;
			}
		});

		suggestionList = (ListView) findViewById(R.id.suggestion_list);
		suggestionList.setAdapter(adapterSuggest);
		suggestionList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (viewFragment != null) {
					if (adapterSuggest.listPage.get(position).feedId
							.equals(viewFragment.id)) {
						Toast.makeText(
								MainActivity.this,
								"You are reading "
										+ adapterSuggest.listPage.get(position).title,
								Toast.LENGTH_SHORT).show();
						return;
					}
				}
				addView(new ViewFragment(MainActivity.this,
						adapterSuggest.listPage.get(position).feedId,
						adapterSuggest.listPage.get(position).title,
						adapterSuggest.listPage.get(position).iconUrl));
				closeSearchPanel();
			}
		});
		viewFragment = new ViewFragment(this,
				"feed/http://bongdaplus.vn/rss/trang-chu.rss",
				"Bóng đá Việt nam", "");

		fragmentSettingPanel = new HomePanel(this, dataUser);

		fragmentManager = getSupportFragmentManager();
		FragmentTransaction trans = fragmentManager.beginTransaction();
		trans.add(R.id.container, viewFragment);
		trans.add(R.id.drawer_panel_setting_container, fragmentSettingPanel);
		trans.commit();

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {

			/** Called when drawer is closed */
			public void onDrawerClosed(View view) {
				invalidateOptionsMenu();
				if (view.getId() == R.id.drawer_panel_setting_container) {
					Log.d(DEBUG_TAG, "Closed setting");
					if (!HomePanel.class.isInstance(fragmentSettingPanel)) {
						addSetingPanel(new HomePanel(MainActivity.this,
								dataUser));
					}
				} else if (view.getId() == R.id.drawer_search) {
					Log.d(DEBUG_TAG, "Closed search");
				}
			}

			/** Called when a drawer is opened */
			public void onDrawerOpened(View view) {
				invalidateOptionsMenu();
				if (view.getId() == R.id.drawer_panel_setting_container) {
					Log.d(DEBUG_TAG, "Opened setting");
				} else if (view.getId() == R.id.drawer_search) {
					Log.d(DEBUG_TAG, "Opened Search");
				}

			}
		};

		// Setting DrawerToggle on DrawerLayout
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		// Enabling Home button
		if (Build.VERSION.SDK_INT >= 14) {
			setHomeButtonEnabled(getActionBar());
		}
		// Enabling Up navigation
		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@SuppressLint("NewApi")
	private void setHomeButtonEnabled(ActionBar bar) {
		bar.setHomeButtonEnabled(true);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add:
			Log.d("ITEM CLICK", "ADD");
			addSetingPanel(new AddPanel(MainActivity.this, dataUser,
					viewFragment.id, viewFragment.title, viewFragment.urlImage));
			openSettingPanel();
			break;
		case R.id.action_search:
			Log.d("ITEM CLICK", "SEARCH");
			if (mDrawerLayout.isDrawerOpen(mDrawerSearch)) {
				mDrawerLayout.closeDrawer(mDrawerSearch);
			} else {
				openSearchPanel();
			}
			break;
		case android.R.id.home:
			if (mDrawerLayout.isDrawerOpen(mDrawerPanelSetting)) {
				mDrawerLayout.closeDrawer(mDrawerPanelSetting);
			} else {
				openSettingPanel();
			}
			break;
		}
		return true;
		// return super.onOptionsItemSelected(item);
	}

	/** Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the drawer is open, hide action items related to the content view
		// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		boolean settingPanelOpen = mDrawerLayout
				.isDrawerOpen(mDrawerPanelSetting);
		boolean searchOpen = mDrawerLayout.isDrawerOpen(mDrawerSearch);
		menu.findItem(R.id.action_add).setVisible(
				!(settingPanelOpen | searchOpen | !isNewPage));
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	class GetSuggest extends AsyncTask<Void, Void, Boolean> {

		private final String keyWord;
		ArrayList<SuggestionPage> listSuggest;
		String SearchResult;

		public GetSuggest(String keyword) {
			this.keyWord = keyword;
			listSuggest = new ArrayList<SuggestionPage>();
			searchRunning = true;
			keyPreviousSearch = keyword;
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			Log.d(DEBUG_TAG, "doinback |" + keyWord + "|");
			SearchResult = handler.makeServiceCall(
					"http://feedly.com/v3/search/feeds?query=" + keyWord
							+ "&count=10", ServiceHandler.GET);
			// Log.v(DEBUG_TAG, "" + SearchResult);
			try {
				JSONObject jsonResult = new JSONObject(SearchResult);
				JSONArray listResult = jsonResult.getJSONArray("results");
				for (int i = 0; i < listResult.length(); i++) {
					JSONObject obj = (JSONObject) listResult.get(i);
					String feedId = obj.getString("feedId");
					long sub = obj.getLong("subscribers");

					String title = getStringAttribute(obj, "title");
					String iconUrl = getStringAttribute(obj, "iconUrl");

					listSuggest.add(new SuggestionPage(feedId, title, iconUrl,
							sub));
				}
			} catch (JSONException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			Log.d(DEBUG_TAG, "post |" + keyWord + "|");
			if (result == true && listSuggest.size() != 0) {
				adapterSuggest.addSuggestPage(listSuggest);
			}
			searchRunning = false;
		}
	}

	public String getStringAttribute(JSONObject object, String name) {
		String result = null;
		try {
			result = object.getString(name);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.d(DEBUG_TAG, "error when get " + name);
		}
		return result;
	}

	public void addView(ViewFragment view) {
		FragmentTransaction trans = fragmentManager.beginTransaction();
		trans.remove(viewFragment);
		viewFragment = view;
		trans.add(R.id.container, viewFragment);
		trans.commit();
		if (isNewFeed(view.id)) {
			isNewPage = true;
		} else {
			isNewPage = false;
		}
		invalidateOptionsMenu();

	}

	public void addSetingPanel(Fragment fragment) {
		FragmentTransaction trans = fragmentManager.beginTransaction();
		trans.remove(fragmentSettingPanel);
		fragmentSettingPanel = fragment;
		trans.add(R.id.drawer_panel_setting_container, fragmentSettingPanel);
		trans.commit();
	}

	@Override
	public void onBackPressed() {
		if (mDrawerLayout.isDrawerOpen(mDrawerSearch)) {
			mDrawerLayout.closeDrawer(mDrawerSearch);
			return;
		}
		if (mDrawerLayout.isDrawerOpen(mDrawerPanelSetting)) {
			mDrawerLayout.closeDrawer(mDrawerPanelSetting);
			return;
		}
		super.onBackPressed();
	}

	public boolean isNewFeed(String feedId) {
		for (int cateIndex = 0; cateIndex < dataUser.size(); cateIndex++) {
			Category category = dataUser.get(cateIndex);
			for (int childIndex = 0; childIndex < category.listChild.size(); childIndex++) {
				if (category.getChild(childIndex).rssId.equals(feedId)) {
					return false;
				}
			}
		}
		return true;
	}

	private String formatKeySearch(String s) {
		return s.replace(" ", "");
	}

	public void openSettingPanel() {
		closeSearchPanel();
		if (!mDrawerLayout.isDrawerOpen(mDrawerPanelSetting)) {
			mDrawerLayout.openDrawer(mDrawerPanelSetting);
		}
	}

	public void closeSettingPanel() {
		if (mDrawerLayout.isDrawerOpen(mDrawerPanelSetting)) {
			mDrawerLayout.closeDrawer(mDrawerPanelSetting);
		}
	}

	public void openSearchPanel() {
		closeSettingPanel();
		if (!mDrawerLayout.isDrawerOpen(mDrawerSearch)) {
			mDrawerLayout.openDrawer(mDrawerSearch);
		}
	}

	public void closeSearchPanel() {
		if (mDrawerLayout.isDrawerOpen(mDrawerSearch)) {
			mDrawerLayout.closeDrawer(mDrawerSearch);
		}
	}
}
